package com.xujichang.viewbinding

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewbinding.ViewBinding
import kotlin.reflect.KClass

interface ViewBindingBase<VB : ViewBinding> {

    fun onBindingCreated()

    fun createBinding(
        inflater: LayoutInflater,
        container: ViewGroup? = null,
        block: ((VB) -> Unit)? = null
    ): VB {
        val vBClass =
            this::class.supertypes.first().arguments.first().type!!.classifier as KClass<VB>
        val result = container?.let { parent ->
            val method =
                vBClass.java.getMethod(
                    "inflate",
                    LayoutInflater::class.java,
                    ViewGroup::class.java,
                    Boolean::class.java
                )
            method.invoke(null, inflater, parent, false)
        } ?: kotlin.run {
            val method =
                vBClass.java.getMethod(
                    "inflate",
                    LayoutInflater::class.java
                )
            method.invoke(null, inflater)
        }
        return with(result) {
            val vb = this as VB
            block?.invoke(vb)
            onBindingCreated()
            vb
        }
    }

    fun createBindingAndReturnView(
        inflater: LayoutInflater,
        container: ViewGroup? = null,
        block: ((VB) -> Unit)? = null
    ): View? =
        createBinding(inflater, container, block).root
}